package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.mapper.SetmealMapper;
import com.sky.utils.BeanCopyUtils;
import com.sky.vo.DishItemVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author MrWang
* @description 针对表【setmeal(套餐)】的数据库操作Service实现
* @createDate 2023-10-18 18:08:58
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
    implements SetmealService{

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    //套餐列表
    @Override
    public Result setmealList(SetmealPageQueryDTO setmealPageQueryDTO) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>()
                .eq(Objects.nonNull(setmealPageQueryDTO.getCategoryId()),Setmeal::getCategoryId,setmealPageQueryDTO.getCategoryId())
                .like(StringUtils.hasText(setmealPageQueryDTO.getName()),Setmeal::getName,setmealPageQueryDTO.getName())
                .eq(Objects.nonNull(setmealPageQueryDTO.getStatus()),Setmeal::getStatus,setmealPageQueryDTO.getStatus());
        Page<Setmeal> page = new Page<>(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        setmealMapper.selectPage(page,queryWrapper);
        List<Setmeal> setmealList = page.getRecords();

        return Result.success(new PageResult(page.getTotal(),setmealList));
    }

    //新增套餐
    @Transactional
    @Override
    public Result saveSetmeal(SetmealDTO setmealDTO) {
        //1.新增套餐信息
        Setmeal setmeal = BeanCopyUtils.copyBean(setmealDTO, Setmeal.class);
        setmealMapper.insert(setmeal);
        //2.新增套餐关联的菜品记录
//        BigDecimal total = BigDecimal.valueOf(0);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
            //给冗余字段赋值..setmeal_dish表的 name 和price
            Dish dish = dishMapper.selectById(setmealDish.getDishId());
            setmealDish.setName(dish.getName());
            setmealDish.setPrice(dish.getPrice());
            //price 算总价
//            BigDecimal multiply = setmealDish.getPrice().multiply(BigDecimal.valueOf(setmealDish.getCopies()));
//            total.add(multiply);
            return setmealDishMapper.insert(setmealDish);
                }).collect(Collectors.toList());
        //3.更新总价
//        setmeal.setPrice(total);
//        setmealMapper.updateById(setmeal);

        return Result.success();
    }

    //批量删除套餐
    @Transactional
    @Override
    public Result deleteSetmeals(String ids) {
        String[] idsArray = ids.split(",");
        for (String id : idsArray) {
            //0.判断是否是起售状态 不可删除
            Setmeal setmeal = setmealMapper.selectById(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE){
//                return Result.error("SETMEAL_ON_SALE");
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
            //1.删除套餐关联的所有菜品记录
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<SetmealDish>()
                    .eq(SetmealDish::getSetmealId,id);
            setmealDishMapper.delete(queryWrapper);
            //2.删除套餐信息
            setmealMapper.deleteById(id);
        }
        return Result.success();
    }

    //根据id查询套餐
    @Transactional
    @Override
    public Result getSetmealById(String id) {
        //1.查询套餐信息
        Setmeal setmeal = setmealMapper.selectById(id);
        //2.查询套餐中菜品列表信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper);
        //3.封装
        SetmealDTO setmealDTO = BeanCopyUtils.copyBean(setmeal, SetmealDTO.class);
        setmealDTO.setSetmealDishes(setmealDishes);

        return Result.success(setmealDTO);
    }

    //修改套餐
    @Transactional
    @Override
    public Result updateSetmeal(SetmealDTO setmealDTO) {
        //1.先删除之前关联的菜品记录
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId,setmealDTO.getId());
        setmealDishMapper.delete(queryWrapper);
        //2.添加新的菜品记录
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDTO.getId());
            return setmealDishMapper.insert(setmealDish);
        }).collect(Collectors.toList());
        //3.更新套餐信息
        Setmeal setmeal = BeanCopyUtils.copyBean(setmealDTO, Setmeal.class);
        setmealMapper.updateById(setmeal);

        return Result.success();
    }

    //套餐启售、停售
    @Transactional
    @Override
    public Result updateSetmealStatus(String status, String id) {
        //1.套餐改成起售状态 需要判断改套餐是否有未启售的菜品
        if (StatusConstant.ENABLE.equals(status)){
            //查询所有该套餐的菜品id列表
            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<SetmealDish>()
                    .eq(SetmealDish::getSetmealId,id);
            List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper);
            List<Long> dishIds = setmealDishes.stream().map(setmealDish -> setmealDish.getDishId())
                    .collect(Collectors.toList());
            //批量查询该套餐所有菜品列表
            List<Dish> dishes = dishMapper.selectBatchIds(dishIds);
            dishes.stream().map(dish -> {
                if (dish.getStatus() == StatusConstant.DISABLE){
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
                return null;
            }).collect(Collectors.toList());
        }
        //2.修改起售状态
        Setmeal setmeal = new Setmeal();
        setmeal.setId(Long.valueOf(id));
        setmeal.setStatus(Integer.valueOf(status));
        setmealMapper.updateById(setmeal);

        return Result.success();
    }


    //C端
    //根据分类id查询套餐列表
    @Override
    public Result getSetmealListByCategoryId(String categoryId) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getStatus,StatusConstant.ENABLE)
                .eq(Setmeal::getCategoryId,categoryId);
        List<Setmeal> setmealList = setmealMapper.selectList(queryWrapper);

        return Result.success(setmealList);
    }

    //根据套餐id查询包含的菜品
    @Override
    public Result getSetmealDishesBySetmealId(String id) {
        List<DishItemVO> dishItemVOList = setmealMapper.getSetmealDishesBySetmealId(id);
        return Result.success(dishItemVOList);
    }


}




